package com.peng.mybatis.reflection.property;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;

import java.util.Iterator;

@Getter
public class PropertyTokenizer implements Iterable<PropertyTokenizer>, Iterator<PropertyTokenizer> {

    /**
     * 例如：班级[0].学生.成绩
     */

    // 班级
    private String name;

    // 班级[0]
    private String indexedName;

    // 0
    private String index;

    // 学生.成绩
    private String children;

    public PropertyTokenizer(final String fullname) {
        int dot = fullname.indexOf(".");
        if (dot != -1) {
            name = fullname.substring(0, dot);
            children = fullname.substring(dot + 1);
        } else {
            name = fullname;
        }
        indexedName = name;
        int leftBracket = fullname.indexOf("[");
        if (leftBracket != -1) {
            index = name.substring(leftBracket + 1, name.length() - 1);
            name = name.substring(0, leftBracket);
        }
    }

    @Override
    public Iterator<PropertyTokenizer> iterator() {
        return this;
    }

    @Override
    public boolean hasNext() {
        return StrUtil.isNotBlank(children);
    }

    @Override
    public PropertyTokenizer next() {
        return new PropertyTokenizer(children);
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("对于PropertyTokenizer的移除是无意义的");
    }

}
